package com.smartfast4j.filesystem.controller;

import com.alibaba.fastjson.JSON;
import com.smartfast4j.common.file.FileService;
import com.smartfast4j.common.file.FileServiceFactory;
import com.smartfast4j.common.file.FileUtil;
import com.smartfast4j.common.file.bean.UploadResult;
import com.smartfast4j.filesystem.SystemConfig;
import com.smartfast4j.filesystem.controller.bean.R;
import org.apache.log4j.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.*;

/**
 * 使用Servlet3.0处理基于webuploader上传插件的文件上传
 * 使用@WebServlet配置UploadServlet的访问路径
 * 使用注解@MultipartConfig将一个Servlet标识为支持文件上传
 */
@WebServlet(name="webUploaderServlet",urlPatterns="/webUploaderServlet")
@MultipartConfig
public class WebUploaderServlet extends HttpServlet {

    private static Logger logger = Logger.getLogger(WebUploaderServlet.class);

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String uploadType = request.getParameter("uploadType");
        //获取上传的文件集合
        Collection<Part> parts = request.getParts();
        //根据用户选择的上传方式获取FileService实例
        FileService fileService = FileServiceFactory.getInstance(uploadType);
        List<UploadResult> uploadResultList = new ArrayList<>();
        //Servlet3.0将multipart/form-data的POST请求封装成Part，通过Part对上传的文件进行操作。
        Map<String,InputStream> uploadFileMap = new HashMap<>();
        for (Part part : parts) {//循环处理上传的文件
            if(part.getContentType() != null){//过滤掉空文件
                //获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
                String header = part.getHeader("content-disposition");
                //获取文件名
                String fileName = getFileName(header);
                uploadFileMap.put(fileName,part.getInputStream());
                //使用fileService上传文件到文件服务器
                //UploadResult uploadResult = fileService.uploadFile(part.getInputStream(), fileName);
                //uploadResultList.add(uploadResult);
            }
        }
        if(uploadFileMap.size()>0){
            //使用fileService批量上传文件到文件服务器
            uploadResultList = fileService.uploadFile(uploadFileMap);
        }
        R r = R.ok(uploadResultList);
        write(response,JSON.toJSONString(r));
    }

    /**
     * 根据请求头解析出文件名
     * 请求头的格式：火狐和google浏览器下：form-data; name="file"; filename="snmp4j--api.zip"
     * IE浏览器下：form-data; name="file"; filename="E:\snmp4j--api.zip"
     *
     * @param header 请求头
     * @return 文件名
     */
    public String getFileName(String header) {
        /**
         * String[] tempArr1 = header.split(";");代码执行完之后，在不同的浏览器下，tempArr1数组里面的内容稍有区别
         * 火狐或者google浏览器下：tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
         * IE浏览器下：tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
         */
        String[] tempArr1 = header.split(";");
        /**
         *火狐或者google浏览器下：tempArr2={filename,"snmp4j--api.zip"}
         *IE浏览器下：tempArr2={filename,"E:\snmp4j--api.zip"}
         */
        String[] tempArr2 = tempArr1[2].split("=");
        //获取文件名，兼容各种浏览器的写法
        String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
        return fileName;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

    private void write(HttpServletResponse response,String str) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(str);
        out.flush();
        out.close();
    }
}